//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/course/course_handouts_model.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/home/resource_item_widget.dart';

/// 课程讲义页面
class CourseHandoutsPage extends StatefulWidget {
  /// 视频id
  final String videoId;

  /// 栏目id
  final String columnId;

  /// 免费标志，true：免费/购买，false：未购买
  final bool free;

  const CourseHandoutsPage({
    super.key,
    required this.videoId,
    required this.columnId,
    required this.free,
  });

  @override
  State<CourseHandoutsPage> createState() => _CourseHandoutsPageState();
}

class _CourseHandoutsPageState extends State<CourseHandoutsPage> {
  late BuildContext _context;

  /// 加载数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关数据方法
  late List<CourseHandoutsModel> _list;

  @override
  void initState() {
    super.initState();
    debugPrint("courseHandoutsPage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _list = [];
    _futureInit = _initData();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("courseHandoutsPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      _list = await CourseDao.listByVideo(
        videoId: widget.videoId,
      );
      map["suc"] = true;
    } catch (e) {
      debugPrint("courseHandoutsPage 页面 -> 加载数据发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("courseHandoutsPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示
  Widget _content() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 24),
      padding: EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: colorWhite1,
        borderRadius: BorderRadius.all(Radius.circular(20)),
      ),
      child: _listItem(),
    );
  }

  /// 滑动组件显示
  _listItem() {
    if (_list.isNotEmpty) {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.separated(
          itemBuilder: _itemBuilder,
          separatorBuilder: _separatorBuilder,
          itemCount: _list.length + 1,
        ),
      );
    } else {
      return showNoData();
    }
  }

  /// 内容组件显示
  Widget? _itemBuilder(BuildContext context, int index) {
    if (index < _list.length) {
      return _resItem(index);
    } else {
      return showListEnd();
    }
  }

  /// 间距显示
  Widget _separatorBuilder(BuildContext context, int index) {
    return recommendItemSeparator();
  }

  /// 内容组件显示
  Widget? _resItem(int index) {
    CourseHandoutsModel model = _list[index];
    return ResourceItemWidget(
      title: model.name!,
      num: model.downloadCount ?? 0,
      subtitle: "",
      columnId: widget.columnId,
      free: widget.free,
      resUrl: model.url!,
      resId: model.id!,
      videoRes: true,
    );
  }
}
